package com.cookie.framework.cloud;

import android.content.Context;
import android.net.Uri;
import android.widget.Toast;

import com.cookie.framework.R;
import com.cookie.framework.utils.LogUtils;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import io.rong.calllib.IRongCallListener;
import io.rong.calllib.IRongReceivedCallListener;
import io.rong.calllib.RongCallClient;
import io.rong.calllib.RongCallCommon;
import io.rong.imlib.IRongCallback;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Message;
import io.rong.message.ImageMessage;
import io.rong.message.LocationMessage;
import io.rong.message.TextMessage;

/**
 * 项目名:    MeetProject
 * 包名:      com.cookie.framework.cloud
 * 文件名:    CloudManager
 * 创建者:    cookie
 * 创建时间:   2020/1/12 18:53
 * 描述:      TODO
 */

public class CloudManager {

    //Url
    public static final String TOKEN_URL = "http://api-cn.ronghub.com/user/getToken.json";

    //key
    public static final String CLOUD_KEY = "8luwapkv84rll";
    public static final String CLOUD_SECRET = "39nHwtGVftT";

    //ObjectName
    public static final String MSG_TEXT_NAME = "RC:TxtMsg";
    public static final String MSG_IMAGE_NAME = "RC:ImgMsg";
    public static final String MSG_LOCATION_NAME = "RC:LBSMsg";

    //msg type
    //普通消息
    public static final String TYPE_TEXT = "type_text";
    //添加好友的消息
    public static final String TYPE_ADD_FRIEND = "type_add_friend";
    //同意添加好友的消息
    public static final String TYPE_AGREE_FRIEND = "type_agree_friend";

    //来电铃声
    public static final String callAudioPath = "http://downsc.chinaz.net/Files/DownLoad/sound1/201501/5363.wav";
    //挂断铃声
    public static final String callAudioHangup = "http://downsc.chinaz.net/Files/DownLoad/sound1/201501/5351.wav";

    private static volatile CloudManager instance = null;

    private CloudManager() {

    }

    public static CloudManager getInstance() {
        if (instance == null) {
            synchronized (CloudManager.class) {
                if (instance == null) {
                    instance = new CloudManager();
                }
            }
        }
        return instance;
    }

    //初始化SDK
    public void initCloud(Context context) {
        RongIMClient.init(context);
    }

    //连接融云服务
    public void connect(String token) {
        RongIMClient.connect(token, new RongIMClient.ConnectCallback() {
            @Override
            public void onTokenIncorrect() {
                LogUtils.e("Token error");
            }

            @Override
            public void onSuccess(String s) {
                LogUtils.e("连接成功" + s);
                CloudManager.getInstance().sendTextMessage("很高兴认识你", "7b86b6cfa0");
            }

            @Override
            public void onError(RongIMClient.ErrorCode errorCode) {
                LogUtils.e("连接失败" + errorCode);
            }
        });
    }

    //断开连接
    public void disconnect() {
        RongIMClient.getInstance().disconnect();
    }

    //退出登录
    public void logout() {
        RongIMClient.getInstance().logout();
    }

    //接收消息的监听器
    public void setOnReceiveMessageListener(RongIMClient.OnReceiveMessageListener listener) {
        RongIMClient.setOnReceiveMessageListener(listener);
    }

    //发送消息的结果回调
    private IRongCallback.ISendMessageCallback iSendMessageCallback = new IRongCallback.ISendMessageCallback() {
        @Override
        public void onAttached(Message message) {
            //消息成功存到本地数据库的回调
        }

        @Override
        public void onSuccess(Message message) {
            //消息发送成功的回调
            LogUtils.i("sendMessage onSuccess");
        }

        @Override
        public void onError(Message message, RongIMClient.ErrorCode errorCode) {
            //消息发送失败的回调
            LogUtils.e("sendMessage onError" + errorCode);
        }
    };

    //发送文本消息
    private void sendTextMessage(String msg, String targetId) {
        TextMessage textMessage = new TextMessage(msg);
        RongIMClient.getInstance().sendMessage(Conversation.ConversationType.PRIVATE,
                targetId,
                textMessage,
                null,
                null,
                iSendMessageCallback);
    }

    private RongIMClient.SendImageMessageCallback sendImageMessageCallback = new RongIMClient.SendImageMessageCallback() {
        @Override
        public void onAttached(Message message) {
            LogUtils.i("onAttached");
        }

        @Override
        public void onError(Message message, RongIMClient.ErrorCode errorCode) {
            LogUtils.i("onError" + errorCode);
        }

        @Override
        public void onSuccess(Message message) {
            LogUtils.i("onSuccess");
        }

        @Override
        public void onProgress(Message message, int i) {
            LogUtils.i("onProgress" + i);
        }
    };

    /**
     * 发送图片消息
     *
     * @param targetId 对方ID
     * @param file     文件
     */
    public void sendImageMessage(String targetId, File file) {
        ImageMessage imageMessage = ImageMessage.obtain(Uri.fromFile(file), Uri.fromFile(file), true);
        RongIMClient.getInstance().sendImageMessage(Conversation.ConversationType.PRIVATE,
                targetId,
                imageMessage,
                null,
                null,
                sendImageMessageCallback);
    }

    //发送位置信息
    public void sendLocationMessage(String mTargetId, double lat, double lng, String poi) {
        LocationMessage locationMessage = LocationMessage.obtain(lat, lng, poi, null);
        Message message = Message.obtain(mTargetId, Conversation.ConversationType.PRIVATE, locationMessage);
        RongIMClient.getInstance().sendLocationMessage(message, null, null, iSendMessageCallback);
    }

    //发送文本消息
    public void sendTextMessage(String msg, String type, String targetId) {
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("msg", msg);
            //如果没有这个type表示普通消息
            jsonObject.put("type", type);
            sendTextMessage(jsonObject.toString(), targetId);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //发送图片消息


    //查询本地的会话记录
    public void getConversationList(RongIMClient.ResultCallback<List<Conversation>> callback) {
        RongIMClient.getInstance().getConversationList(callback);
    }

    //加载本地的历史记录
    public void getHistoryMessages(String targetId, RongIMClient.ResultCallback<List<Message>> callback) {
        RongIMClient.getInstance().getHistoryMessages(Conversation.ConversationType.PRIVATE,
                targetId, -1, 1000, callback);
    }

    //获取服务器的历史记录
    public void getRemoteHistoryMessages(String targetId, RongIMClient.ResultCallback<List<Message>> callback) {
        RongIMClient.getInstance().getRemoteHistoryMessages(Conversation.ConversationType.PRIVATE,
                targetId, 0, 20, callback);
    }

    //---------------------------------------------call api---------------------

    private void startCall(Context context, String targetId, RongCallCommon.CallMediaType type) {
        //检查设备可用
        if (!isVoIPEnabled(context)) {
            return;
        }
        if (!isConnect()) {
            Toast.makeText(context, context.getString(R.string.text_server_status), Toast.LENGTH_SHORT).show();
            return;
        }
        List<String> userIds = new ArrayList<>();
        userIds.add(targetId);
        RongCallClient.getInstance().startCall(
                Conversation.ConversationType.PRIVATE,
                targetId,
                userIds,
                null,
                type,
                null);
    }

    //音频
    public void startAudioCall(Context context, String targetId) {
        if (!CloudManager.getInstance().isVoIPEnabled(context)){
            return;
        }
        startCall(context, targetId, RongCallCommon.CallMediaType.AUDIO);
    }

    //视频
    public void startVideoCall(Context context, String targetId) {
        if (!CloudManager.getInstance().isVoIPEnabled(context)){
            return;
        }
        startCall(context, targetId, RongCallCommon.CallMediaType.VIDEO);
    }

    //监听音频通话
    public void setReceivedCallListener(IRongReceivedCallListener listener) {
        if (listener == null) {
            return;
        }
        RongCallClient.setReceivedCallListener(listener);
    }

    //接听
    public void acceptCall(String callId) {
        RongCallClient.getInstance().acceptCall(callId);
    }

    //挂断
    public void hangUpCall(String callId) {
        RongCallClient.getInstance().hangUpCall(callId);
    }

    //切换媒体
    public void changeCallMediaType(RongCallCommon.CallMediaType mediaType) {
        RongCallClient.getInstance().changeCallMediaType(mediaType);
    }

    //切换摄像头
    public void switchCamera() {
        RongCallClient.getInstance().switchCamera();
    }

    //摄像头开关
    public void setEnableLocalVideo(boolean enable) {
        RongCallClient.getInstance().setEnableLocalVideo(enable);
    }

    //音频开关
    public void setEnableLocalAudio(boolean enable) {
        RongCallClient.getInstance().setEnableLocalAudio(enable);
    }

    //免提开关
    public void setEnableSpeakerphone(boolean enable) {
        RongCallClient.getInstance().setEnableSpeakerphone(enable);
    }

    //开启录音
    public void startAudioRecording(String filePath) {
        RongCallClient.getInstance().startAudioRecording(filePath);
    }

    //关闭录音
    public void stopAudioRecording() {
        RongCallClient.getInstance().stopAudioRecording();
    }

    //监听通话状态
    public void setVoIPCallListener(IRongCallListener listener) {
        if (null == listener) {
            return;
        }
        RongCallClient.getInstance().setVoIPCallListener(listener);
    }

    //检查设备是否可用通话
    public boolean isVoIPEnabled(Context context) {
        if (!RongCallClient.getInstance().isVoIPEnabled(context)) {
            Toast.makeText(context, context.getString(R.string.text_devices_not_supper_audio), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    /**
     * 是否连接
     *
     * @return
     */
    private boolean isConnect() {
        return RongIMClient.getInstance().getCurrentConnectionStatus()
                == RongIMClient.ConnectionStatusListener.ConnectionStatus.CONNECTED;
    }
}
